`
https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/
`

/**
 * @param {number[]} nums
 * @param {number} x
 * @return {number}
 */
var minOperations = function (nums, x) {
  // 题目是从两边开始拿元素，这样的话中间就会剩下一个子数组
  // 那么便可以把题目等价为寻找和为 sum(x) - x 的最长子数组
  const sum = nums.reduce((acc, cur) => {
    return acc + cur
  }, 0)
  const need = sum - x

  let window = 0
  let left = 0, right = 0

  let res = -1

  while (right < nums.length) {
    // 扩大窗口
    window += nums[right]
    right++

    while (window >= need) {
      if (window === need) {
        res = Math.max(res, right - left)
      }
      // 缩小窗口
      window -= nums[left]
      left++
    }
  }

  return res === -1 ? -1 : nums.length - res
};